<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
} else if (!isRootAdm()) {
    echo ROOT_ONLY;
    exit;
}

$_SESSION['tab'] = 3;
$act = getHttpVal('act', '');
writeLog('# act = '.$act, true);

if (strlen($act) > 0) { // Perform the specified action
  
  $otp = strtolower(getHttpVal('otp', ''));
  $pin = getHttpVal('pin', '');
  $notes = getHttpVal('notes', '');
  
  if (strlen($otp) > 0) {
    $devId = substr($otp, 0, DEVICE_ID_LEN);
    $a = getKeyInfo($devId);
    if (!isset($a['keyid'])) {
  	  $_SESSION['alert'] = 'Yubikey '.$devId.' is not in the database.';
  	  header('Location: index.php');
  	  exit;
    }
    $keyid = $a['keyid'];
    $keyOwner = clientOfYubikey($a['keyid']);
    $keyOwnerEmail = $a['email'];
    delAdminByKeyId($keyid);
    
    if ($keyOwner != 1) { // Key is owned by a client already
	  $_SESSION['alert'] = 'The Yubikey was owned by Client: '.
		makePopupURL('edit_client.php?client='.$keyOwner, $keyOwner, 500).'<p>';
    } else {
  	  $_SESSION['alert'] = '';
    }
  } else {
  	  $keyOwnerEmail = '';
  }
  
  if (strcmp($act,'add_client') == 0) { // Add a client and an admin for it

    $perm = getHttpVal('perm', 0);
	$email = getHttpVal('email', '');
	$apiKey = getHttpVal('api_key', '');

	if (($id=getClientByEmail($email)) > 0) {
	  $_SESSION['alert'] .= 'Failed to add the new Client! Email '.$email.' is used by '.
		makePopupURL('edit_client.php?client='.$id, 'Client-'.$id, 500);
	}
	
	// Add a new client

    else if (($client=addClient($email, $apiKey, $perm, $notes)) > 0) { 
      // Client added
      if (strlen($otp) > 0) { // OTP exits, add the adm yubikey
      
        if (addNewAdmKeyAndPin($keyid, $pin, $devId, $notes, $client)) {

          if ($client != $_SESSION['client']) {
      		if (updClientOfKey($keyid, $client)) {
      		  $_SESSION['alert'] .= 'Admin Yubikey '.$devId .
				' added for '.
        		makePopupURL('edit_client.php?client='.$client, 'Client-'.$client, 500).
					' successfully';
			  if ($perm >= 1 && $perm <= 2) {
			  	$strs = array(); 		  	
			  	$strs['__KEY_ID__']=$devId; $strs['__PW__']=$pin; $strs['__EMAIL__']=$email;
          		$content = replaceInTemplate('welcome.txt', $strs);          		
          		sendMail($email, 'Your Yubikey management account is activated',
          			$content, $admEmail, $keyOwnerEmail);
			  } else {
			  	writeLog('# perm = '.$perm.' activation email unsent.');
			  }
      		} else {		
      			$_SESSION['alert'] .= 'Failed to update the owner of the Yubikey to the client! '.$contactAdm;
      		}
          }  	        	
        } else {
          $_SESSION['alert'] .= 'Failed to associate the Yubikey for the client admin, check input and try again';
        }
      } else {
      	$_SESSION['alert'] .= 'Client-'.
      		makePopupURL('edit_client.php?client='.$client, $client, 500).
			' added successfully';
      }
    } else {
      $_SESSION['alert'] .= 'Failed to add a new client, check input and try again';
    }
   
  } // End of add a new client + admin yubikey
  
  else if (strcmp($act,'add_admin_key') == 0) { // Add an admin Yubikey to a client
  
  	$client=getHttpVal('client_id', 0); 
	updClientPerm($client, 2);
	updClientOfKey($keyid, $client);
	$stmt = 'INSERT INTO admin (keyid, note, pin, ip, creation, client) VALUES ('.
		$keyid.','.
		mysql_quote($notes).','.
		mysql_quote(aesEncrypt($pin)).','.
		mysql_quote($_SERVER['REMOTE_ADDR']).','.
		'NOW(),'.
		$client.
		')';
	writeLog($stmt, true);

    if (query($stmt)) {
        $_SESSION['alert'] = 'Admin Yubikey '.$devId .' added for '.
        	makePopupURL('edit_client.php?client='.$client, 'Client-'.$client, 500).
			' successfully';
    } else {
    	$_SESSION['alert'] .= 'Failed to add admin Yubikey '.$devId .' for a client '.$client;
    }
    
    $email = getClientEmail($client);
   	$strs = array();
	$strs['__KEY_ID__']=$devId; $strs['__PW__']=$pin; $strs['__EMAIL__']=$email;
    $content = replaceInTemplate('welcome.txt', $strs);          		
    sendMail($email, 'Your Yubikey management account is activated',
    		$content, $admEmail, $keyOwnerEmail);

  } // End add a new admin yubikey to a client
  
  header('Location: index.php');
  exit;

} // End of action

?>

<form name=add_client id=add_client method=POST action=add_client.php autocomplete=off>
<input type=hidden name=act value=add_client>

<table border=0 width=100%>
<tr><td align=left colspan=9>

 <table border=0> 
 <tr><td valign=top width=40><img src=images/arrow.jpg></td>
 <td valign=top nowrap align=left><font color=#008080 size=2><b>
 Add a new client & an<br>admin Yubikey for it:</font></b></td>
 <td width=10></td>
 <td>
 A Client is an issuer that issues Yubikeys to its users and use this server for OTP 
 validation and Yubikey management. It can log in to this console to manage Yubikeys 
 issued by it. It can also create other sub-clients.
 </td></tr>
 </table>

</td></tr>

<tr><td align=right><font size=2>
Client admin email:
</td>
<td align=left><font size=2>
<input name=email id=email size=40 maxlength=100 class=inputtxt value="">
</td></tr>

<tr><td align=right><font size=2>Permission:</td>
<td align=left>
<select name=perm class=inputtxt>
<option value="2">Verify OTP + Manage Yubikeys</option>
<option value="3">Verify OTP Only</option>
</select>
</td></tr>

<tr><td align=right><font size=2>
<a target=_new href=http://yubico.com/developers/api/>
<font color=#008800> API Key: <b>?</b></font></a>
</td>
<td align=left><font size=2>
<input name=api_key id=api_key size=40 maxlength=100 class=inputtxt 
 value="<?php echo genAPIKey();?>" readonly="readonly">
</td>
<td align=left>
<font size=1 color=#aaaaaa><< Auto-generated. It is used to verify OTP validation
requests & responses.</font>
</td></tr>

<tr><td align=right><font size=2>Note about this client:
<br><font size=1 color=#aaaaaa>
(Max is <?php echo MAX_NOTE;?> characters)
</td>
<td align=left>	
<textarea name=notes maxlength=<?php echo MAX_NOTE;?> rows=2 
cols=30 class=inputtxt onkeyup="return ismaxlength(this)"></textarea>
</td>
</tr>

<tr><td align=right><font size=2>
An OTP or device ID (modhex mode)
from the Yubikey to be issued: 
</td>
<td align=left><font size=2>
<input name=otp id=otp size=40 maxlength=100 class=inputtxt value="">
</td>
<td align=left>
<font size=1 color=#aaaaaa><< If left empty, only the Client will be added
</td>
</tr>

<tr><td align=right><font size=2>
Password: 
</td>
<td align=left><font size=2>
<input name=pin id=pin size=40 maxlength=100 class=inputtxt value="<?php echo genStrongPw();?>">
</td>
<td align=left>
<font size=1 color=#aaaaaa><< Auto-generated. The client admin use the password + Yubikey to log in to 
the management console.</font>
</td></tr>

<tr><td align=center colspan=2>
<input type=button class=buttonLinkO value="Add the Client" 
 onClick="submitAddClient()">
</td></tr></table></form>	

</td></tr></table>
</form>

<hr size=1>

<form name=add_admin_key id=add_admin_key method=POST action=add_client.php autocomplete=off>
<input type=hidden name=act value=add_admin_key>
<table border=0 width=100%>
<tr><td align=left colspan=9>

 <table border=0><tr><td valign=top width=40><img src=images/arrow.jpg></td>
 <td valign=top nowrap align=left>
 <font color=#008080 size=2><b>Add an admin Yubikey to an existing Client:
 </b></font></h3></td></tr>
 </table>

</td></tr>

<tr><td align=right><font size=2>
Client ID: <font size=1><a href="javascript:expandtab('maintab',3)">(find a client)</a></font>
</td>
<td align=left><font size=2>
<input name=client_id size=5 maxlength=9 class=inputtxt value="">
</td></tr>

<tr><td align=right><font size=2>
An OTP or device ID (modhex mode)
from the Yubikey to be issued: 
</td>
<td align=left><font size=2>
<input name=otp id=otp size=40 maxlength=100 class=inputtxt value="">
</td></tr>

<tr>
<td align=right><font size=2>
Password:
</td>
<td align=left><font size=2>
<input name=pin id=pin size=40 maxlength=100 class=inputtxt value="<?php echo genStrongPw();?>">
</td>

<td align=left>
<font size=1 color=#aaaaaa><< Auto-generated. The client admin use the password + 
Yubikey to log in to the management console.</font>
</td>
</tr>

<tr><td align=right><font size=2>Note about this admin Yubikey:
<br><font size=1 color=#aaaaaa>
(Max is <?php echo MAX_NOTE;?> characters)
</td>
<td align=left>	
<textarea name=notes maxlength=<?php echo MAX_NOTE;?> rows=2 
cols=30 class=inputtxt onkeyup="return ismaxlength(this)"></textarea>
</td>
</tr>

<tr><td align=center colspan=2>
<input type=button class=buttonLinkO value="Add the Yubikey" onClick="submitAddAdminKey()">
</td></tr></table></form>	

</td></tr></table>
</form>

</body>
</html>
